package top.codedance.iotp.registy.net.handle.action;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.enums.HttpStatus;
import top.codedance.iotp.common.util.HttpRequestUtil;
import top.codedance.iotp.registy.RegistryApplication;
import top.codedance.iotp.registy.net.handle.AdapterController;
import org.apache.log4j.Logger;

public class RegistyClientController extends AdapterController {
    private static Logger logger = RegistryApplication.getLogger(RegistyClientController.class);

    public String doSubHandler(JSONObject body) {
        try {
            if(!RegistryApplication.isElectioning) {
                if (RegistryApplication.isMaster) {
                    String deviceId = body.getString("deviceId");
                    String server = body.getString("server");
                    if (RegistryApplication.checkServer(server)) {
                        RegistryApplication.addClient(deviceId, server);
                        logger.debug("Client registing: " + server + ":" + deviceId);
                    } else {
                        return errResponse(HttpStatus.NOT_FOUND.getCode(), "Not found server.");
                    }
                } else {
                    JSONObject post = HttpRequestUtil.post(RegistryApplication.masterHost + "/rest/api/client/register", body.toJSONString());
                    logger.debug("Proxy client registing");
                    if (post.getIntValue("status") == 200) {
                        return okResponse(post.getJSONObject("data"));
                    } else {
                        return errResponse(post.getIntValue("status"), post.getString("message"));
                    }
                }
            }
            JSONObject data = new JSONObject();
            return okResponse(data);
        } catch (Exception e) {
            logger.debug(e.getMessage());
            return response500( "Programe exception");
        }
    }
}
